<template>
  <!-- 新增部门的弹层 -->
  <el-dialog :title="showTitle" :visible="showDialog" close-on-press-escape @close="btnCancel">
    <!-- 表单组件 el-form，通过 label-width 设置 label 的宽度  -->
    <!-- 匿名插槽 -->
    <el-form ref="formDataRef" v-loading="dialogLoading" label-width="120px" :model="formData" :rules="rules">
      <el-form-item label="部门名称" prop="name">
        <el-input v-model="formData.name" style="width:80%" placeholder="1-50个字符" />
      </el-form-item>
      <el-form-item label="部门编码" prop="code">
        <el-input v-model="formData.code" style="width:80%" placeholder="1-50个字符" />
      </el-form-item>
      <el-form-item label="部门负责人" prop="manager">
        <el-select v-model="formData.manager" :loading="selectLoading" style="width:80%" placeholder="请选择" @focus="getEmployeeSimple">
          <el-option v-for="item in peoples" :key="item.id" :lable="item.username" :value="item.username" />
        </el-select>
      </el-form-item>
      <el-form-item label="部门介绍" prop="introduce">
        <el-input v-model="formData.introduce" style="width:80%" placeholder="1-300个字符" type="textarea" :rows="3" />
      </el-form-item>
    </el-form>
    <!-- el-dialog 有专门放置底部操作栏的插槽，具名插槽 -->
    <el-row slot="footer" type="flex" justify="center">
      <!-- 列被分为 24 -->
      <el-col :span="6">
        <el-button :loading="dialogLoading" type="primary" size="small" @click="btnOk">确定</el-button>
        <el-button size="small" @click="btnCancel">取消</el-button>
      </el-col>
    </el-row>
  </el-dialog>
</template>

<script>
import { getDepartments, addDepartments, getDepartDetail, updateDepartments } from '@/api/departments'
import { getEmployeeSimple } from '@/api/employees'

export default {
  name: 'AddDept',
  props: {
    showDialog: {
      type: Boolean,
      default: false
    },
    treeNode: {
      type: Object,
      default: null
    }
  },
  data() {
    const checkName = async(_, value, callback) => {
      const { depts } = await getDepartments()
      let isRepeat = false
      if (this.treeNode.id) {
        isRepeat = depts.filter(item => item.pid === this.formData.pid && item.id !== this.formData.id).some(item => item.name === value)
      } else {
        isRepeat = depts.filter(item => item.pid === this.treeNode.id).some(item => item.name === value)
      }
      isRepeat ? callback(new Error(`当前部门下已经有 ${value} 的部门了`)) : callback()
    }
    const checkCode = async(_, value, callback) => {
      const { depts } = await getDepartments()
      let isRepeat = false
      if (this.treeNode.id) {
        isRepeat = depts.some(item => item.code === value && item.id !== this.formData.id)
      } else {
        isRepeat = depts.some(item => item.code === value)
      }
      isRepeat ? callback(new Error(`当前已经有 ${value} 的部门编码了`)) : callback()
    }
    return {
      // 定义表单数据
      formData: {
        name: '', // 部门名称，必填 1-50 个字符，同级部门中禁止出现重复部门
        code: '', // 部门编码，必填 1-50 个字符，部门编码在整个模块中都不允许重复
        manager: '', // 部门管理者，必填
        introduce: '' // 部门介绍，必填 1-300 个字符
      },
      // 定义校验规则
      rules: {
        name: [
          { required: true, message: '部门名称不能为空', trigger: 'blur' },
          { min: 1, max: 50, message: '部门名称要求1-50个字符', trigger: 'blur' },
          { validator: checkName, trigger: 'blur' }
        ],
        code: [
          { required: true, message: '部门编码不能为空', trigger: 'blur' },
          { min: 1, max: 50, message: '部门编码要求1-50个字符', trigger: 'blur' },
          { validator: checkCode, trigger: 'blur' }
        ],
        manager: [
          { required: true, message: '部门负责人不能为空', trigger: 'blur' }
        ],
        introduce: [
          { required: true, message: '部门介绍不能为空', trigger: 'blur' },
          { trigger: 'blur', min: 1, max: 300, message: '部门介绍要求1-50个字符' }
        ]
      },
      peoples: [],
      selectLoading: false,
      dialogLoading: false
    }
  },
  computed: {
    showTitle() {
      return this.formData.id ? '编辑部门' : '新增子部门'
    }
  },
  methods: {
    async getEmployeeSimple() {
      this.selectLoading = true
      const peoples = await getEmployeeSimple()
      this.peoples = peoples
      this.selectLoading = false
    },
    btnOk() {
      this.$refs.formDataRef.validate(async valid => {
        if (valid) {
          if (this.formData.id) {
            await updateDepartments(this.formData)
          } else {
            await addDepartments({
              ...this.formData,
              pid: this.treeNode.id
            })
          }
          this.$emit('addDepts')
          this.$emit('update:showDialog', false)
        }
      })
    },
    btnCancel() {
      this.formData = {
        name: '',
        code: '',
        manager: '',
        introduce: ''
      }
      this.$refs.formDataRef.resetFields()
      this.$emit('update:showDialog', false)
    },
    async getDepartDetail(id) {
      this.dialogLoading = true
      this.formData = await getDepartDetail(id)
      this.dialogLoading = false
    }
  }
}
</script>
